# coding: utf-8
from datetime import datetime

from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import HttpResponseServerError
from django.shortcuts import render
from django.urls import reverse
from django.views import View
from leancloud import Object
from leancloud import Query
from leancloud.errors import LeanCloudError
import leancloud
import openpyxl
from . import Common
import time, datetime
import io
from openpyxl.writer.excel import save_virtual_workbook

#进行核算
class TotalCal(View):
    def get(self, request):
        return render(request, 'total_cal.html', {})
    def post(self, request):
        if request.POST.get('year') == None or request.POST.get('month') == None:
            return render(request, 'total_cal.html', {})
        timeArray = [request.POST.get('year'), request.POST.get('month')]
        calResultDict = {}
        isContinue = True
        buyInfoDict = {}
        sellInfoDict = {}
        while isContinue:
            #查找当月的采购表
            buyRecordInfo = leancloud.Object.extend('BuyRecord')
            query = buyRecordInfo.query
            query.equal_to('Year', int(timeArray[0]))
            query.equal_to('Month', int(timeArray[1]))
            # query.not_equal_to('IsCal', True)
            query.limit(1000)
            buyRecordInfoQ = query.find()
            isBuyContinue = True
            if len(buyRecordInfoQ) < 1:
                isBuyContinue = False
            #转换所有的单位
            for elem in buyRecordInfoQ:
                resultAmount, resultUnit = Common.UnitTransform(elem.get("ItemName"), elem.get("Amount"), elem.get("Unit"))
                if elem.get("ItemName") not in buyInfoDict:
                    buyInfoDict[elem.get("ItemName")] = [elem.get("Amount"), elem.get("Unit")]
                else:
                    if elem.get("Amount") is not None:
                        buyInfoDict[elem.get("ItemName")][0] = buyInfoDict[elem.get("ItemName")][0] + elem.get("Amount")
                elem.set("IsCal", True)
            buyRecordInfo.save_all(buyRecordInfoQ)
            #查找当月的销售表
            sellRecordInfo = leancloud.Object.extend('SellRecord')
            query = sellRecordInfo.query
            query.equal_to('Year', int(timeArray[0]))
            #todo
            # query.equal_to('Month', int(8))
            query.equal_to('Month', int(timeArray[1]))
            # query.not_equal_to('IsCal', True)
            query.limit(1000)
            sellRecordInfoQ = query.find()
            isSellContinue = True
            if len(sellRecordInfoQ) < 1:
                isSellContinue = False
            #采购和销售当月都处理完毕的话，就退出循环
            if not isBuyContinue and not isSellContinue:
                isContinue = False
                break
            #转换所有的单位
            for elem in sellRecordInfoQ:
                resultAmount, resultUnit = Common.UnitTransform(elem.get("ItemName"), elem.get("SellAmount"), elem.get("Unit"))
                #将销售表按成分分解为细节物品
                makeUpList = Common.MakeUpConvert(elem.get("ItemName"), resultAmount, resultUnit)
                for elem2 in makeUpList:
                    if elem2[0] not in sellInfoDict:
                        sellInfoDict[elem2[0]] = [elem2[1], elem2[2]]
                elem.set("IsCal", True)
            sellRecordInfo.save_all(sellRecordInfoQ)
            #采购-销售得出核算
            for elemKey in buyInfoDict:
                if elemKey in calResultDict:
                    if buyInfoDict[elemKey][0] is not None:
                        calResultDict[elemKey][3] = calResultDict[elemKey][3] + buyInfoDict[elemKey][0]
                else:
                    itemSort = Common.GetItemSortDict(elemKey)
                    # 名称,单位,上月结存,本月进货,本月销售,本月结存
                    calResultDict[elemKey] = [elemKey, buyInfoDict[elemKey][1], 0, buyInfoDict[elemKey][0], 0, itemSort]
            for elemKey in sellInfoDict:
                if elemKey in calResultDict:
                    calResultDict[elemKey][4] = calResultDict[elemKey][4] + sellInfoDict[elemKey][0]
                else:
                    itemSort = Common.GetItemSortDict(elemKey)
                    # 名称,单位,上月结存,本月进货,本月销售,本月结存
                    calResultDict[elemKey] = [elemKey, sellInfoDict[elemKey][1], 0, 0, sellInfoDict[elemKey][0], itemSort]
            #获取上月盘点表
            preMonth = int(timeArray[1]) - 1
            preYear = int(timeArray[0])
            if preMonth == 0:
                preMonth = 12
                preYear = timeArray[0] - 1
            inventory = leancloud.Object.extend('Inventory')
            query = inventory.query
            query.equal_to('Year', timeArray[0])
            query.equal_to('Month', timeArray[1])
            query.limit(1000)
            inventoryQ = query.find()
            if len(inventoryQ) > 0:
                for elem in inventoryQ:
                    #转换单位
                    resultAmount, resultUnit = Common.UnitTransform(elem.get("ItemName"), elem.get("Amount"), elem.get("Unit"))
                    if elem in calResultDict:
                        calResultDict[elemKey][2] = calResultDict[elemKey][2] + resultAmount
                    else:
                        itemSort = Common.GetItemSortDict(elemKey)
                        calResultDict[elemKey] = [elemKey, resultUnit, resultAmount, 0, 0, itemSort]
            isContinue = False
        print(calResultDict)
        #核算结果入库
        if len(calResultDict) > 0:
            allTodo = []
            Todo = leancloud.Object.extend('CalReslut')
            for key, elem in calResultDict.items():
                todo = Todo()
                todo.set("Year", timeArray[0])
                todo.set("Month", timeArray[1])
                todo.set("ItemName", elem[0])
                todo.set("Unit", elem[1])
                todo.set("PreAmount", elem[2])
                todo.set("BuyAmount", elem[3])
                todo.set("SellAmount", elem[4])
                todo.set("ItemSort", elem[5])
                allTodo.append(todo)
            Todo.save_all(allTodo)
        #生成核算excel表格
        return render(request, 'total_cal.html', {})

class TotalCalExport(View):
    def get(self, request):
        return render(request, 'total_cal.html', {})
    def post(self, request):
        if request.POST.get('year') == None or request.POST.get('month') == None:
            return render(request, 'total_cal.html', {})
        timeArray = [request.POST.get('year'), request.POST.get('month')]
        itemSort = request.POST.get('sort')
        #查询对于的核算表格
        calReslut = leancloud.Object.extend('CalReslut')
        query = calReslut.query
        query.equal_to('Year', timeArray[0])
        query.equal_to('Month', timeArray[1])
        if itemSort == "酒水":
            query.equal_to('ItemSort', "酒水")
        else:
            query.not_equal_to('ItemSort', "酒水")
        query.limit(1000)
        calReslutQ = query.find()
        if len(calReslutQ) > 0:
            wb = openpyxl.Workbook()
            ws = wb.worksheets[0]
            title = str(calReslutQ[0].get("Year")) + "年" + str(calReslutQ[0].get("Month")) + "月" + itemSort + "核算表"
            ws.title = title
            excelFirst = ["名称", "单位", "上月结存", "本月进货", "本月销售"]
            j = 0
            for elem in excelFirst:
                j = j + 1
                ws.cell(row=1,column=j,value=elem)
            i = 1;
            for elem in calReslutQ:
                i = i + 1
                excelElem = [elem.get("ItemName"), elem.get("Unit"), elem.get("PreAmount"), elem.get("BuyAmount"), elem.get("SellAmount")]
                k = 0
                for elemK in excelElem:
                    k = k + 1
                    ws.cell(row=i,column=k,value=elemK)
            # wb.save(title + ".xlsx")
            file_name = str(calReslutQ[0].get("Year")) + "_" + str(calReslutQ[0].get("Month")) + "_TotalCal.xlsx"
            # response = HttpResponse()
            # response['content'] = save_virtual_workbook(wb)
            # response['content_type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            # response['content_disposition'] = 'attachment; filename=' + title + '.xlsx'
            response = HttpResponse(content=save_virtual_workbook(wb), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
            response['Content-Disposition'] = 'attachment;name=file; filename='+file_name
            return response
        else:
            return render(request, 'total_cal.html', {})

